package cn.csust.net2.manager.client.module;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.csust.net2.manager.client.Manager;
import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.ux.BeanGridPanel;
import cn.csust.net2.manager.client.ux.ExpandTree;
import cn.csust.net2.manager.shared.po.Academy;
import cn.csust.net2.manager.shared.po.Banji;
import cn.csust.net2.manager.shared.po.Vote;
import cn.csust.net2.manager.shared.po.VoteAnswer;
import cn.csust.net2.manager.shared.service.VoteManagerService;
import cn.csust.net2.manager.shared.service.VoteManagerServiceAsync;
import cn.csust.net2.manager.shared.service.VoteService;
import cn.csust.net2.manager.shared.util.ClassForNameAble;
import cn.csust.net2.manager.shared.util.Constant;
import cn.csust.net2.manager.shared.util.POConstant;
import cn.csust.net2.manager.shared.vo.Config;
import cn.csust.net2.manager.shared.vo.TreeNode;

import com.extjs.gxt.charts.client.Chart;
import com.extjs.gxt.charts.client.model.ChartModel;
import com.extjs.gxt.charts.client.model.axis.XAxis;
import com.extjs.gxt.charts.client.model.axis.YAxis;
import com.extjs.gxt.charts.client.model.charts.BarChart;
import com.extjs.gxt.charts.client.model.charts.BarChart.Bar;
import com.extjs.gxt.charts.client.model.charts.CylinderBarChart;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.TabPanel.TabPosition;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FileUploadField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.rpc.AsyncCallback;

@ClassForNameAble
public class VoteManager extends BaseModule {
//	User user = null;
	//服务组件
	private VoteManagerServiceAsync managerService;
//	private ByGradeServiceAsync byGradeservice;
	
	//创建vote的表单
	private ExpandTree treePanel;
	private ComboBox<ModelData> comboBox;
	private ListStore<ModelData> comStore;
	private TextField<String> topicText;
	private DateField startDate;
	private DateField endDate ;
	private TimeField startTime ;
	private TimeField endTime;
	private TreePanel<ModelData> tree;
	private TreeStore<ModelData> store ;
	private HtmlEditor editor;
	private LayoutContainer addContainer ;
	private FileUploadField filePicture;
	private FileUploadField fileFlash ;
	
	
	private List<Integer> banjiIDList;
	//存放voteAnswer
	private Set<VoteAnswer> answerSet ;
	//创建投票
	private Vote vote ;
	//用于记录创建投票时选项个数
	private int count;
	//记录查询 对应vote 的 voteAnswer 的数量
	private int sizeFlag ;
	//图标
	private Chart chart ;
	
	public VoteManager() {
		init();
		this.setText("管理投票");
		this.setId("管理投票");
		this.setClosable(true);
		this.setLayout(new FitLayout());
		
		TabPanel folder = new TabPanel();
		folder.setSize("%100", "%100");
		folder.setTabPosition(TabPosition.BOTTOM);
		/*
		 * 创建投票
		 */
		TabItem createItem = new TabItem("创建投票");
		createItem.setSize("%100", "%100");
		createItem.setLayout(new RowLayout(Style.Orientation.HORIZONTAL));
		createItem.setScrollMode(Scroll.AUTO);
		createItem.add(getFormPanel(), new RowData(0.59, 430, new Margins(5, 5,
				5, 5)));
		createItem.add(createPreviewPanel(), new RowData(0.39, 430, new Margins(5, 5,
				5, 5)));
		
		/*
		 * 编辑与统计
		 */
		TabItem managerItem = new TabItem("编辑与统计");
		managerItem.setLayoutOnChange(true);
		managerItem.setSize("%100", "%100");
		managerItem.setLayout(new RowLayout(Style.Orientation.HORIZONTAL));
		managerItem.setScrollMode(Scroll.AUTO);
		managerItem.add(getBeanGridPanel(), new RowData(0.6, 1, new Margins(
				5, 5, 5, 5)));
		managerItem.add(getChart(), new RowData(0.38, 400, new Margins(5, 5, 5,
				5)));

		folder.add(createItem);
		folder.add(managerItem);
		this.add(folder);

	}
	
	
	private void init(){
	//	byGradeservice=GWT.create(ByGradeService.class);
		managerService = GWT.create(VoteManagerService.class);
		answerSet = new LinkedHashSet<VoteAnswer>();
		vote = new Vote();
		store = new TreeStore<ModelData>();
	}

	/*
	 * 显示投票的表格
	 */
	public BeanGridPanel<Vote> getBeanGridPanel() {
		final BeanGridPanel<Vote> grid = new BeanGridPanel<Vote>(new Vote(),managerService);
		grid.setAutoLoad(false);
		grid.setEditAble(false);
		grid.setAddButton(false);
		grid.setDeleteButton(false);
		grid.setModifyButton(false);
		grid.setSaveButton(false);
		grid.createDefault();
		Map<String,Object> config = new HashMap<String,Object>();
		config.put(Constant.PUBUSERID, new Long(App.getUser().getUserID()));
		grid.load(config);
		grid.getGrid()
				.getSelectionModel()
				.addSelectionChangedListener(
						new SelectionChangedListener<BeanModel>() {
							@Override
							public void selectionChanged(
									SelectionChangedEvent<BeanModel> se) {
								Vote vote = se.getSelectedItem().getBean();
								banjiIDList = null;
								loadBanjiIDList(vote);
								loadChart(vote);
								
							}
						});
		
		Button edit = new Button("设置投票班级",new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(grid.getGrid().getSelectionModel().getSelectedItem()==null){
					MessageBox.alert("提示","请选择一个投票！" , null);
				}else{
					Vote vote = grid.getGrid().getSelectionModel().getSelectedItem().getBean();					
					initTree(vote);
					
				}
			}
		});
		grid.getToolBar().add(edit);
		return grid;
	}

	//加载vote绑定的班级
	private void loadBanjiIDList(Vote vote){
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(VoteManagerService.VOTEID, vote.getVoteId());
		managerService.findVoteBanjiIDListByPaging(config, new AsyncCallback<List<Integer>>() {
			
			@Override
			public void onSuccess(List<Integer> result) {
				banjiIDList = result;				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("", "加载相关班级信息失败", null);
				
			}
		});
	}
	
	/*
	 * 设置关联的学生
	 */
	private void initTree(final Vote vote) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(ExpandTree.TEACHER_ADD, false);
		map.put(ExpandTree.CHECKABLE, true);		
		treePanel = new ExpandTree(Banji.class,true,map) {
			@Override
			protected void load(Object loadConfig, Map<String, Object> configs,
					AsyncCallback<List<TreeNode>> callback) {

				managerService.getChildren((TreeNode) loadConfig, configs, callback);
			}

			@Override
			protected void load(String[] items) {
				Config c = new Config();
				c.put(ExpandTree.GRADE_ITEMS, items);
				treePanel.load(Banji.class,c);
			}
		};
		treePanel.setHeading(vote.getTitle());
		treePanel.getTree().setAutoExpand(true);

		final Window treeWindow = new Window();
		treeWindow.setLayout(new FitLayout());
		
		
		treePanel.getTree().setCheckable(false);
		treeWindow.add(treePanel);
		treeWindow.setSize(250, 500);
		
		final PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(VoteManagerService.VOTEID, vote.getVoteId());
		treeWindow.addButton(new Button("编辑", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {

						if(banjiIDList == null){
							MessageBox.alert("", "绑定班级未完成,稍后重试", null);
							return;
						}
						System.out.println(banjiIDList+ "+++++++++++++++++++++++++++++++++++");
						treePanel.getTree().setCheckable(true);
						List<BeanModel> items  = treePanel.getTree().getStore().getAllItems();

						for(BeanModel bm : items){
							if(bm.getBean() instanceof Banji){
								if(banjiIDList.contains(((Banji)bm.getBean()).getBanjiID())){
									System.out.println("找到了:"+((Banji)bm.getBean()).getBanjiName());
									treePanel.getTree().setChecked(bm, true);
								}
							}
						}
						
						for(BeanModel bm : items) {
							if(bm.getBean() instanceof Academy){
								System.out.println("展开了：" +((Academy) bm.getBean()).getAcademyName());
								treePanel.getTree().setExpanded(bm, false);
								treePanel.getTree().setExpanded(bm, true);
							}
						}

			}
		}));
		
		treeWindow.addButton(new Button("保存", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				List<BeanModel> models = treePanel.getTree().getCheckedSelection();
				System.out.println(models.size()+" this is size");
				List<Integer> numberList = new ArrayList<Integer>();
				for(BeanModel model:models){					
					if(model.getBean() instanceof Banji){
						numberList.add(((Banji)model.getBean()).getBanjiID());
					}
				}
				PagingLoadConfig config = new BasePagingLoadConfig();
				config.set(VoteManagerService.VOTEID,vote.getVoteId());
				config.set(VoteManagerService.BANJIIDLIST,numberList);				
				managerService.saveVoteBanjiIDListByPaging(config, new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						MessageBox.alert("提示", "保存失败", null);
						
					}

					@Override
					public void onSuccess(Void result) {
						MessageBox.alert("提示", "保存成功", null);
						
					}
					
				});

				treeWindow.hide();
			}
		}));
		treeWindow.show();
	}
	

	public void loadChart(final cn.csust.net2.manager.shared.po.Vote vote){
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(VoteManagerService.VOTEID, vote.getVoteId());
		if (vote != null) {
			managerService.findVoteAnswersByPaging(config,
					new AsyncCallback<PagingLoadResult<VoteAnswer>>() {
						@Override
						public void onSuccess(
								PagingLoadResult<VoteAnswer> result) {
							List<VoteAnswer> answers = result.getData();
							final Map<VoteAnswer, Integer> resultMap = new LinkedHashMap<VoteAnswer, Integer>();
							sizeFlag=answers.size();
							for (int i = 0; i < answers.size(); i++) {
								final VoteAnswer answer = answers.get(i);
								managerService.findVoteResultsByAnswerID(answer.getAnswerId(), new AsyncCallback<Integer>() {

									@Override
									public void onFailure(Throwable caught) {
										MessageBox.alert("警告","获取选票数据失败："+answer.getText(), null);
										
									}

									@Override
									public void onSuccess(Integer result) {
										resultMap.put(answer,result);	
										if(resultMap.size()==sizeFlag){											
											chart.setChartModel(getChartModel(vote,resultMap));
											chart.show();
										}
									}
									
								});
							}
						}

						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("", "get voteanswer failed", null);

						}
					});
		}
	}
	
    public ChartModel getChartModel(final cn.csust.net2.manager.shared.po.Vote vote,final Map<VoteAnswer, Integer> resultMap) { 
    	int step = 10;
		int max = 100;
		//当投票大于当前 值时  最大值也要变大
		for(int num:resultMap.values()){
			if (num > 100) {
				max = (3 + (num - 100) / 50) * 50;
				step = max / 10;
			}
		}

		
	      ChartModel cm = new ChartModel(vote.getTitle(),  
	          "font-size: 14px; font-family: Verdana; text-align: center;");  
	      cm.setBackgroundColour("#ffffff");
	      CylinderBarChart bchart = new CylinderBarChart();  
	      bchart.setColour("#440088");  
	      bchart.setAlpha(.8f);  
//	      bchart.setTooltip("#val#票");
	      String [] lables = null;
    	  lables = new String[resultMap.size()]; 
	      int s = 0;
		  for(VoteAnswer an : resultMap.keySet()){
			  Bar bar = new BarChart.Bar(resultMap.get(an));
			  bar.setTooltip(an.getText()+" #val#票");
			  bar.set(VoteService.VOTEANSWERID, an.getAnswerId());
			  bchart.addBars(bar);
			  lables[s] = new String(an.getText());
			  s++; 			 
		  }  
      
    	  XAxis xa = new XAxis();  
	      xa.setLabels(lables);  
	      xa.setZDepth3D(5);  
	      xa.setTickHeight(4);  
	      xa.setOffset(true);  
	      xa.setColour("#909090");  
	      cm.setXAxis(xa);  
	      YAxis ya = new YAxis();  
	      ya.setSteps(step);  
	      ya.setMax(max);  
	      cm.setYAxis(ya);            
	      cm.addChartConfig(bchart); 
	      
	      return cm;  
	    }  
	
	


	public Chart getChart() {
		 String url = !Manager.isExplorer() ? "../../" : "";    
		 url += "gxt/chart/open-flash-chart.swf";
		chart = new Chart(url);
		chart.setBorders(true);
		Map<VoteAnswer, Integer> resultMap = new HashMap<VoteAnswer, Integer>();
		for(int i=0;i<4;i++){
			VoteAnswer an = new VoteAnswer();
			an.setText("选项"+(i+1));
			resultMap.put(an, Random.nextInt(100));
		}
		Vote voteTest = new Vote();
		voteTest.setTitle("随机测试");
		chart.setChartModel(getChartModel(voteTest, resultMap));
//		chart.setChartModel(new ChartModel("测试","font-size: 14px; font-family: Verdana; text-align: center;"));
		chart.setSize(440, 300);
		return chart;
	}

	
	/*
	 * 注意！！！！！
	 * 此表单预留了两个控件 分别用来 上传 图片和flash
	 * 数据库中也预留了 picture 和 flash 字段
	 * 暂时注释 以防备用
	 */
	public FormPanel getFormPanel() {
		// 表单开始
		FormData formData = new FormData("100%");
		final FormPanel formPanel = new FormPanel();
		formPanel.setLayoutOnChange(true);
		formPanel.setFrame(true);
		formPanel.setHeading("编辑投票");
		formPanel.setSize(600, -1);

		LayoutContainer main = new LayoutContainer();
		main.setLayout(new ColumnLayout());

		LayoutContainer left = new LayoutContainer();
		left.setStyleAttribute("paddingRight", "10px");
		FormLayout layout = new FormLayout();
		// layout.setLabelAlign(LabelAlign.TOP);
		left.setLayout(layout);

		startDate = new DateField();
		startDate.setFieldLabel("开始日期");
		left.add(startDate, formData);

		endDate = new DateField();
		endDate.setFieldLabel("结束日期");
		left.add(endDate, formData);

		comboBox = new ComboBox<ModelData>();
		comStore = new ListStore<ModelData>();
		comboBox.setStore(comStore);
		comboBox.setDisplayField("name");
		comboBox.setFieldLabel("选择类型");
		BaseModelData data1 = new BaseModelData();
		data1.set("name", "文字类型");
		data1.set("value", POConstant.VOTETYPE.Text);
		
		
//		BaseModelData data2 = new BaseModelData();
//		data2.set("name", "图片类型");
//		data2.set("value", POConstant.VOTETYPE.Picture);
//		BaseModelData data3 = new BaseModelData();
//		data3.set("name", "flash类型");
//		data3.set("value", POConstant.VOTETYPE.Flash);
//		BaseModelData data4 = new BaseModelData();
//		data4.set("name", "文字和图片类型");
//		data4.set("value", POConstant.VOTETYPE.TextAndPicture);
//		BaseModelData data5 = new BaseModelData();
//		data5.set("name", "文字和flash类型");
//		data5.set("value", POConstant.VOTETYPE.TextAndFlash);
//		BaseModelData data6 = new BaseModelData();
//		data6.set("name", "图片和flash类型");
//		data6.set("value", POConstant.VOTETYPE.PictureAndFlash);
//		BaseModelData data7 = new BaseModelData();
//		data7.set("name", "文字图片flash类型");
//		data7.set("value", POConstant.VOTETYPE.All);
//		
		
		comStore.add(data1);
		//comStore.add(data2);
		//comStore.add(data3);
		//comStore.add(data4);
		//comStore.add(data5);
		//comStore.add(data6);
		//comStore.add(data7);
		comboBox.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {

			@Override
			public void selectionChanged(SelectionChangedEvent<ModelData> se) {
				if (se.getSelectedItem().get("value")
						.equals(POConstant.VOTETYPE.Text)) {
					editor.setEnabled(true);
					fileFlash.setEnabled(false);
					filePicture.setEnabled(false);
				} 
//				else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.Picture)) {
//					editor.setEnabled(false);
//					filePicture.setEnabled(true);
//					fileFlash.setEnabled(false);
//				} else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.Flash)) {
//					editor.setEnabled(false);
//					fileFlash.setEnabled(true);
//					filePicture.setEnabled(false);
//				} else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.TextAndPicture)) {
//					editor.setEnabled(true);
//					filePicture.setEnabled(true);
//					fileFlash.setEnabled(false);
//				} else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.TextAndFlash)) {
//					editor.setEnabled(true);
//					fileFlash.setEnabled(true);
//					filePicture.setEnabled(false);
//				} else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.PictureAndFlash)) {
//					editor.setEnabled(false);
//					fileFlash.setEnabled(true);
//					filePicture.setEnabled(true);
//				} else if (se.getSelectedItem().get("value")
//						.equals(POConstant.VOTETYPE.All)) {
//					editor.setEnabled(true);
//					fileFlash.setEnabled(true);
//					filePicture.setEnabled(true);
//				}
				editor.setValue("");
			}
		});
		left.add(comboBox, formData);

		LayoutContainer right = new LayoutContainer();
		right.setStyleAttribute("paddingLeft", "10px");
		layout = new FormLayout();
		right.setLayout(layout);

		startTime = new TimeField();
		startTime.setFieldLabel("开始时间");
		right.add(startTime, formData);

		endTime = new TimeField();
		endTime.setFieldLabel("结束时间");
		right.add(endTime, formData);

		topicText = new TextField<String>();
		topicText.setFieldLabel("投票主题");
		topicText.setEnabled(false);

		editor = new HtmlEditor();
		editor.setFieldLabel("文本编辑器");
		editor.setHeight(200);
		editor.setValue("请先\"选择类型\",在此处编辑文字后请点击\"设置为本次投票主题按钮\"作为主题，或点击\"添加为备选项\"为本次投票添加备选项...");
		editor.setEnabled(false);

		addContainer = new LayoutContainer(new ColumnLayout());
		LayoutContainer bottomLeft = new LayoutContainer(new FormLayout());
		bottomLeft.setStyleAttribute("paddingRight", "10px");

		LayoutContainer bottomRight = new LayoutContainer(new FormLayout());
		bottomRight.setStyleAttribute("paddingRight", "10px");

		//上传图片的控件 暂时不添加
//		filePicture = new FileUploadField();
//		filePicture.setName("uploadedPicture");
//		filePicture.setFieldLabel("选择图片");
//		filePicture.setWidth("%100%");
		
//		bottomLeft.add(filePicture, formData);// 去除注释添加控件

//		fileFlash = new FileUploadField();
//		fileFlash.setName("uploadedFlash");
//		fileFlash.setFieldLabel("选择flash");
//		fileFlash.setWidth("%100%");

//		bottomRight.add(fileFlash, formData);// 去除注释添加控件

		addContainer.add(bottomLeft, new ColumnData(.5));
		addContainer.add(bottomRight, new ColumnData(.5));

		main.add(left, new ColumnData(.5));
		main.add(right, new ColumnData(.5));

		formPanel.add(main, formData);
		formPanel.add(topicText, formData);
		formPanel.add(editor, formData);
		formPanel.add(addContainer, formData);

		Button topicButton = new Button("设置为本次投票主题",
				new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
						if(editor.getValue()==null||editor.getValue().trim().equals("")||editor.getValue().trim().equals("<br>")){
							MessageBox.alert("警告", "不能添加空主题！", null);
							return;
						}
						topicText.setValue(editor.getValue());
						editor.setValue("");
					}
				});
		Button answerButton = new Button("添加为备选项",
				new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
						VoteAnswer answer = new VoteAnswer();
						BaseTreeModel model = new BaseTreeModel();
						

						if (editor.getValue() != null
								&& !editor.getValue().trim().equals("")||editor.getValue().trim().equals("<br>")) {
							answer.setText(editor.getValue());
							BaseTreeModel m = new BaseTreeModel(model);
							m.set("name", answer.getText());
							store.add(model, m, false);
						}
//						if (filePicture.getValue() != null
//								&& !filePicture.getValue().trim().equals("")) {
//							answer.setPicture(filePicture.getValue());
//							BaseTreeModel m = new BaseTreeModel(model);
//							m.set("name", answer.getPicture());
//							store.add(model, m, false);
//						}
//						if (fileFlash.getValue() != null
//								&& !fileFlash.getValue().trim().equals("")) {
//							answer.setFlash(fileFlash.getValue());
//							BaseTreeModel m = new BaseTreeModel(model);
//							m.set("name", answer.getFlash());
//							store.add(model, m, false);
//						}
						
						
						if(model.getChildCount() <= 0){
							
							MessageBox.alert("提示", "不能添加空选项！", null);
							return;
						}
						
						model.set("name", "选项" + (++count));
						editor.setValue("");
//						filePicture.setValue("");
//						fileFlash.setValue("");
						model.set("answer", answer);
						answer.setVote(vote);
						answerSet.add(answer);
						store.add(model, true);
						tree.getSelectionModel().select(model, false);
						tree.setExpanded(model, true);
					}
				});
		formPanel.addButton(topicButton);
		formPanel.addButton(answerButton);
		formPanel.show();
		return formPanel;
	}

	public ContentPanel createPreviewPanel() {
		
		Button delete = new Button("删除选中项",
				new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
						
						if(tree==null||tree.getSelectionModel()==null||tree.getSelectionModel().getSelectedItem()==null){
							return;
						}
						BaseTreeModel model = (BaseTreeModel) tree
						.getSelectionModel().getSelectedItem();
						answerSet.remove(model.getProperties().get("answer"));
						store.remove(model);
					}
				});

		Button submit = new Button("提交", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if(startDate.getDatePicker().getValue() == null||startTime.getDateValue()==null||endDate.getDatePicker().getValue()==null||endTime.getDateValue()==null){
					MessageBox.alert("提示", "日期设置不正确", null);
					return;
				}
				if(topicText.getValue().equals("")){
					MessageBox.alert("", "请设置投票主题", null);
					return;
				}
				vote.setPubUserId(App.getUser().getUserID());
				String sDate = DateTimeFormat.getFormat("yyyy-MM-dd").format(
						startDate.getDatePicker().getValue());
				String sTime = DateTimeFormat.getFormat("HH:mm:ss").format(
						startTime.getDateValue());

				Timestamp ts = Timestamp.valueOf(sDate + " " + sTime);
				vote.setStartTime(ts);
				String eDate = DateTimeFormat.getFormat("yyyy-MM-dd").format(
						endDate.getDatePicker().getValue());
				String eTime = DateTimeFormat.getFormat("HH:mm:ss").format(
						endTime.getDateValue());
				Timestamp es = Timestamp.valueOf(eDate + " " + eTime);
				vote.setEndTime(es);
				
				if(startDate.getDatePicker().getValue().after(endDate.getDatePicker().getValue()) ){
					MessageBox.alert("", "开始日期必须在结束时间之前！", null);
					return;
				}else if(startDate.getDatePicker().getValue().equals(endDate.getDatePicker().getValue())){
					if(startTime.getDateValue().after(endTime.getDateValue())){
						MessageBox.alert("", "开始时间必须在结束时间之前！", null);
						return;
					}
				}
				
				
				vote.setTitle(topicText.getValue());
				vote.setType((Integer) comboBox.getSelection().get(0)
						.get("value"));
				vote.setAnswerSet(answerSet);
				managerService.save(vote, new AsyncCallback<Void>() {
					@Override
					public void onSuccess(Void result) {
						MessageBox.alert("通知", "保存成功！", null);

					}

					@Override
					public void onFailure(Throwable caught) {
						MessageBox.alert("通知", "保存失败！", null);
					}
				});
			}
		});

		tree = new TreePanel<ModelData>(store);
		tree.setDisplayProperty("name");
		tree.setAutoSelect(true);
		ContentPanel treePa = new ContentPanel();
		treePa.setScrollMode(Scroll.AUTO);
		treePa.setLayout(new FitLayout());
		treePa.add(tree);
		treePa.addButton(delete);
		treePa.addButton(submit);
		treePa.setHeading("选项预览");
		return treePa;
	}

}
